﻿//using System;
//using System.ComponentModel;
//using System.Configuration;
//using System.Data;
//using System.Data.SqlClient;
//using SqlSystemWatcher.Common;

//namespace SqlSystemWatcher.DatabaseFileLog
//{
//    public class DatabaseFileLoggerCore
//    {
//        private readonly DataSet _ds;

//        private readonly string _instanceName;

//        public DatabaseFileLoggerCore(string sqlServerInstanceName)
//        {
//            _ds = new DataSet();

//            _instanceName = sqlServerInstanceName;
//        }

//        public void DoIt()
//        {
//            using (var backgroundWorker = new BackgroundWorker())
//            {
//                backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
//                backgroundWorker.RunWorkerAsync();
//            }
//        }

//        private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs e)
//        {
//            string connectionString = @"Data Source=" + _instanceName +
//                                      ";Initial Catalog=master; Integrated Security=True";

//            const string sqlCommandText = @"SELECT
//                                            'InstanceName'			= @@SERVERNAME,
//                                            'DatabaseId'			= db.database_id,
//                                            'DatabaseName'			= db.name,
//                                            'GroupId'				= mf.data_space_id,
//                                            'FileId'				= mf.file_id,
//                                            'FileGuid'				= mf.file_guid,
//                                            --'FileType'				= mf.type,
//                                            'FileTypeDesc'			= mf.type_desc,
//                                            'FileName'				= mf.name,
//                                            'FilePath'				= mf.physical_name,
//                                            'SizeInMb'				= mf.size * 8 / 1024,
//                                            'MaxSizeInMb'			= CASE WHEN max_size = -1 
//								                                            THEN -1
//								                                            ELSE (mf.max_size * 8.0)/1024.0
//						                                              END,
//                                            'GrowthInPercent'		= CASE WHEN mf.is_percent_growth <> 0
//								                                            THEN mf.growth
//								                                            ELSE NULL
//						                                              END,
//                                            'GrowthInMb'			= CASE WHEN mf.is_percent_growth = 0
//								                                            THEN mf.growth * 8 / 1024.0
//						                                              END,
//                                            'OwnerSid'				= SUSER_SNAME(db.owner_sid),
//                                            'CreateDate'			= db.create_date,
//                                            'CompatibilityLevel'	= db.compatibility_level,
//                                            'CollationName'			= db.collation_name,
//                                            --'UserAccess'			= db.user_access,
//                                            'UserAccessDesc'		= db.user_access_desc,
//                                            'IsReadOnly'			= db.is_read_only,
//                                            'IsAutoCloseOn'			= db.is_auto_close_on,
//                                            'IsAutoShrinkOn'		= db.is_auto_shrink_on,
//                                            --'State'					= db.state,
//                                            'StateDesc'				= db.state_desc,
//                                            --'RecoveryModel'			= db.recovery_model,
//                                            'RecoveryModelDesc'		= db.recovery_model_desc
//                                            FROM sys.databases          db
//                                            INNER JOIN sys.master_files mf ON db.database_id   = mf.database_id
//                                            INNER JOIN sys.sysfiles     sf ON mf.file_id       = sf.fileid
//                                                                          AND mf.data_space_id = sf.groupid";
//            try
//            {
//                if (_ds.Tables.Contains("RawDatabaseFileLog"))
//                {
//                    _ds.Tables["RawDatabaseFileLog"].Clear();
//                }
//                else
//                {
//                    _ds.Tables.Add("RawDatabaseFileLog");
//                }

//                var sqlDa = new SqlDataAdapter {SelectCommand = new SqlCommand(sqlCommandText)};
//                sqlDa.SelectCommand.Connection = new SqlConnection(connectionString);
//                sqlDa.Fill(_ds.Tables["RawDatabaseFileLog"]);

//                var customException = new CustomException();
//                customException.WriteInfoScreen(CustomException.InfoScreenLevel.Information, _instanceName,
//                                                "DatabaseFileLoggerCore",
//                                                "Write RawDatabaseFileLog entries into DataFileLog table");

//                Guid sqlDatabaseFileLogSetId = Guid.NewGuid();

//                foreach (DataRow rawLogRow in _ds.Tables["RawDatabaseFileLog"].Rows)
//                {
//                    string conStr = ConfigurationManager.ConnectionStrings["ConStr"].ToString();
//                    var sqlConnection = new SqlConnection(conStr);

//                    var sqlDaDataFileLog = new SqlDataAdapter
//                        {
//                            InsertCommand = new SqlCommand("[dbo].[DataFileLogInsert]")
//                        };
//                    sqlDaDataFileLog.InsertCommand.Connection = sqlConnection;
//                    sqlDaDataFileLog.InsertCommand.Connection.Open();
//                    sqlDaDataFileLog.InsertCommand.CommandType = CommandType.StoredProcedure;
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@DatabaseFileLogSetId",
//                                                                           sqlDatabaseFileLogSetId);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@InstanceName", rawLogRow["InstanceName"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@DatabaseName", rawLogRow["DatabaseName"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@GroupId", rawLogRow["GroupId"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@FileId", rawLogRow["FileId"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@FileGuid", rawLogRow["FileGuid"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@FileTypeDesc", rawLogRow["FileTypeDesc"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@FileName", rawLogRow["FileName"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@FilePath", rawLogRow["FilePath"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@SizeInMb", rawLogRow["SizeInMb"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@MaxSizeInMb", rawLogRow["MaxSizeInMb"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@GrowthInPercent",
//                                                                           rawLogRow["GrowthInPercent"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@GrowthInMb", rawLogRow["GrowthInMb"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@OwnerSid", rawLogRow["OwnerSid"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@CreateDate", rawLogRow["CreateDate"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@CompatibilityLevel",
//                                                                           rawLogRow["CompatibilityLevel"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@CollationName", rawLogRow["CollationName"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@UserAccessDesc",
//                                                                           rawLogRow["UserAccessDesc"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@IsReadOnly", rawLogRow["IsReadOnly"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@IsAutoCloseOn", rawLogRow["IsAutoCloseOn"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@IsAutoShrinkOn",
//                                                                           rawLogRow["IsAutoShrinkOn"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@StateDesc", rawLogRow["StateDesc"]);
//                    sqlDaDataFileLog.InsertCommand.Parameters.AddWithValue("@RecoveryModelDesc",
//                                                                           rawLogRow["RecoveryModelDesc"]);
//                    sqlDaDataFileLog.InsertCommand.ExecuteNonQuery();
//                    sqlDaDataFileLog.InsertCommand.Connection.Close();
//                }

//                UpdateInstanceLastCheck(_instanceName);
//            }
//            catch (Exception ex)
//            {
//                //UpdateSqlServerErrorLog("SqlServerSessionLog update was not possible.", InstanceName, "", ex);

//                var errorLoggerCore = new ErrorLoggerCore(_instanceName, ex.Message);
//                errorLoggerCore.DoIt();
//            }
//        }

//        //private bool UpdateSqlServerErrorLog(string customMessage, string instanceName, string databaseName,
//        //                                     Exception ex)
//        //{
//        //    try
//        //    {
//        //        var customException = new CustomException();
//        //        customException.WriteException2Screen("SqlServerErrorLog update was not possible.", instanceName, "", ex);

//        //        //string conStrMonitorDb =
//        //        //    ConfigurationManager.ConnectionStrings["abc"].ConnectionString;

//        //        //var sqlDaLogInsert = new SqlDataAdapter { InsertCommand = new SqlCommand("[dbo].[ErrorLogInsert]") };
//        //        //sqlDaLogInsert.InsertCommand.CommandType = CommandType.StoredProcedure;
//        //        //sqlDaLogInsert.InsertCommand.Connection = new SqlConnection(conStrMonitorDb);

//        //        //sqlDaLogInsert.InsertCommand.Parameters.AddWithValue("@IntstanceName", instanceName);
//        //        //sqlDaLogInsert.InsertCommand.Parameters.AddWithValue("@LastModifiedDate", DateTime.Now);
//        //        //sqlDaLogInsert.InsertCommand.Parameters.AddWithValue("@Message", ex.Message);
//        //        //sqlDaLogInsert.InsertCommand.Parameters.AddWithValue("@Operation", customMessage);

//        //        //sqlDaLogInsert.InsertCommand.Connection.Open();
//        //        //sqlDaLogInsert.InsertCommand.ExecuteNonQuery();
//        //        //sqlDaLogInsert.InsertCommand.Connection.Close();

//        //        return true;
//        //    }
//        //    catch (Exception)
//        //    {
//        //        var customException = new CustomException();
//        //        return customException.WriteException2Screen("SqlServerErrorLog update was not possible.", instanceName,
//        //                                                     "", ex);
//        //    }
//        //}

//        private bool UpdateInstanceLastCheck(string instanceName)
//        {
//            try
//            {
//                //string conStrMonitorDb =
//                //    ConfigurationManager.ConnectionStrings["abc"].ConnectionString;

//                //var sqlDaSqlInstance = new SqlDataAdapter
//                //{
//                //    UpdateCommand =
//                //        new SqlCommand("[dbo].[InstanceSessionLogLastCheckUpdate]")
//                //};
//                //sqlDaSqlInstance.UpdateCommand.CommandType = CommandType.StoredProcedure;
//                //sqlDaSqlInstance.UpdateCommand.Connection = new SqlConnection(conStrMonitorDb);
//                //sqlDaSqlInstance.UpdateCommand.Parameters.AddWithValue("@InstanceName", instanceName);
//                //sqlDaSqlInstance.UpdateCommand.Parameters.AddWithValue("@SessionLogLastCheck",
//                //                                                       DateTime.Now);

//                //sqlDaSqlInstance.UpdateCommand.Connection.Open();
//                //sqlDaSqlInstance.UpdateCommand.ExecuteNonQuery();
//                //sqlDaSqlInstance.UpdateCommand.Connection.Close();

//                return true;
//            }
//            catch (Exception ex)
//            {
//                var errorLoggerCore = new ErrorLoggerCore(_instanceName, ex.Message);
//                errorLoggerCore.DoIt();
//                return false;
//            }
//        }
//    }
//}

